package com.sample.servlet;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sample.info.InputInfo;
import com.sample.info.OutputInfo;

public class HttpSerializableServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

	    System.out.println("HttpSerializableServlet Start doPost");

	    // オブジェクトを取得
	    ObjectInputStream ois = new ObjectInputStream(req.getInputStream());

	    InputInfo info = null;
	    try {
		    info = (InputInfo) ois.readObject();
	    } catch (ClassNotFoundException cnfe) {
	    	cnfe.printStackTrace();
	    }
	    ois.close();

	    // コンソール出力
	    System.out.println(info.toString());

	    // 返却オブジェクト作成
	    OutputInfo output = new OutputInfo();
	    output.setDate(new Date());
	    output.setName("Serializable Output Object");
	    output.getHash().put("params1", "Output1");
	    output.getHash().put("params2", "Output2");
	    output.setNum(output.getNum() + 1);

	    // OutputInfo送信
//	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    ObjectOutputStream oos = new ObjectOutputStream(resp.getOutputStream());
	    oos.writeObject(output);

	    oos.flush();
	    oos.close();

	    resp.getOutputStream().flush();
	    resp.getOutputStream().close();

       System.out.println("HttpSerializableServlet End doPost");
	}

//	@Override
//	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
//			throws ServletException, IOException {
//
//	    System.out.println("HttpStandardServlet Start doGet");
//
//        String param1 = req.getParameter("param1");
//        String param2 = req.getParameter("param2");
//
//        resp.getOutputStream().print("GET " + param1 + " " + param2);
//
//       System.out.println("HttpStandardServlet End doGet");
//	}
//
//	private void sleep(int sec) {
//		try {
//			Thread.sleep(sec);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//	}

}
